# agents/factor_agents/cerydra_agent.py
from .base_factor_agent import BaseFactorAgent
from game_engine.game_state import FactorDevelopment, GameWorld
import numpy as np

class CerydraAgent(BaseFactorAgent):
    """刻律德菈智能体 - 战技辅助特化 [火种：律法]"""
    
    def __init__(self, factor: FactorDevelopment, game_world: GameWorld):
        super().__init__(factor, game_world)
        self.personality_traits.update({
            "aggression": 0.3,      # 低攻击性
            "caution": 0.9,         # 极高谨慎性
            "order_focus": 0.95,    # 秩序专注
            "tactical_priority": 0.9  # 战术优先
        })
        self.active_buffs = {}
        self.battle_analysis = {}
        self.last_tactical_update = 0
    
    def make_decision(self, current_time: int) -> str:
        """刻律德菈的决策逻辑"""
        situation = self.evaluate_situation()
        
        # 战术分析更新
        if current_time - self.last_tactical_update > 20:
            self.last_tactical_update = current_time
            return "update_battle_analysis"
        
        # 维持重要buff
        expiring_buffs = [buff for buff, info in self.active_buffs.items() 
                         if info["duration"] < 10]
        if expiring_buffs:
            most_important = max(expiring_buffs, 
                               key=lambda x: self.active_buffs[x]["priority"])
            return f"refresh_buff:{most_important}"
        
        # 应用战术buff
        if situation["allies_need_buffs"]:
            ally = situation["allies_need_buffs"][0]
            buff_type = self._determine_best_buff(ally)
            return f"apply_{buff_type}:{ally.name}"
        
        # 战场控制
        if situation["enemy_formation_broken"]:
            return "exploit_formation_break"
        
        # 标准战术行动
        return "execute_tactical_maneuver"
    
    def evaluate_situation(self) -> Dict:
        """评估当前局势"""
        nearby_factors = self.get_nearby_factors(30.0)
        
        allies_need_buffs = []
        enemy_formation_broken = False
        
        for factor in nearby_factors:
            if not self._is_potential_threat(factor):
                # 检查盟友是否需要buff
                has_important_buff = any(
                    buff_info["target"] == factor.name and buff_info["priority"] >= 7
                    for buff_info in self.active_buffs.values()
                )
                if not has_important_buff and factor.is_alive:
                    allies_need_buffs.append(factor)
        
        # 简单的阵型判断
        ally_positions = [f.current_location for f in nearby_factors 
                         if not self._is_potential_threat(f)]
        if len(ally_positions) >= 3:
            formation_cohesion = self._calculate_formation_cohesion(ally_positions)
            enemy_formation_broken = formation_cohesion < 0.6
        
        return {
            "allies_need_buffs": allies_need_buffs,
            "enemy_formation_broken": enemy_formation_broken,
            "active_buffs_count": len(self.active_buffs),
            "tactical_advantage": self._calculate_tactical_advantage()
        }
    
    def _determine_best_buff(self, ally: FactorDevelopment) -> str:
        """确定最佳增益效果"""
        ally_type = ally.factor_type
        
        if ally_type.value in ["万敌", "遐蝶"]:  # 攻击型
            return "attack_buff"
        elif ally_type.value in ["风堇", "长夜月"]:  # 辅助型
            return "support_buff"
        elif ally_type.value in ["缇宝", "赛飞儿"]:  # 机动型
            return "mobility_buff"
        else:
            return "defense_buff"
    
    def _calculate_formation_cohesion(self, positions: List[Tuple]) -> float:
        """计算阵型凝聚力"""
        if len(positions) < 2:
            return 1.0
        
        total_distance = 0
        count = 0
        for i in range(len(positions)):
            for j in range(i+1, len(positions)):
                total_distance += self._calculate_distance(positions[i], positions[j])
                count += 1
        
        avg_distance = total_distance / count if count > 0 else 0
        # 理想距离为15，计算凝聚力
        return max(0, 1 - abs(avg_distance - 15) / 30)
    
    def _calculate_tactical_advantage(self) -> float:
        """计算战术优势"""
        # 简化计算：基于buff数量和阵型
        buff_score = len(self.active_buffs) * 0.1
        formation_score = 0.3  # 假设值
        
        return min(1.0, buff_score + formation_score)